/**
 * FileName: DocumentHandler
 * Author:   Ren
 * Date:     2019/5/5 15:25
 * Description: word工具類
 */
package com.yq588.demo.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class DocumentHandler {

    private static Configuration configuration = null;
    private static Map<String, Template> allTemplates = null;

    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(DocumentHandler.class, "/template");
        allTemplates = new HashMap<>();
        try {
            allTemplates.put("trouble", configuration.getTemplate("trouble.ftl"));
            allTemplates.put("risktrouble", configuration.getTemplate("risktrouble.ftl"));
            allTemplates.put("disobey", configuration.getTemplate("disobey.ftl"));
            allTemplates.put("disobeytally", configuration.getTemplate("disobeytally.ftl"));
            allTemplates.put("troubletall", configuration.getTemplate("troubletall.ftl"));
            allTemplates.put("personexcel", configuration.getTemplate("personexcel.xml"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private DocumentHandler() {
        throw new AssertionError();
    }
    public static File createDoc(Map<?, ?> dataMap, String type) {
        String name = type+ (int) (Math.random() * 100000) + ".doc";
        File f = new File("c:\\"+name);
        Template t = allTemplates.get(type);
        try {
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }
}


